package com.gitee.zhanyao.itext.util;

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhanyao
 */
@Slf4j
public class PdfPictureUtil {

    private PdfPictureUtil() {}

    public static void addImage(String source, String target, int pageNum, String imagePath, float imageWidth, float imageHeight,
            float x, float y, float width, float height) {
        try (PdfDocument pdfDocument = new PdfDocument(new PdfReader(source), new PdfWriter(target))) {
            PdfPage pdfPage = pdfDocument.getPage(pageNum);
            PdfCanvas pdfCanvas = new PdfCanvas(pdfPage);
            Image image = new Image(ImageDataFactory.create(imagePath)).setWidth(imageWidth).setHeight(imageHeight);
            Paragraph paragraph = new Paragraph().add(image);
            Rectangle rectangle = new Rectangle(x, y, width, height);
            Canvas canvas = new Canvas(pdfCanvas, rectangle);
            canvas.add(paragraph);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }
    }

}
